package net.asfun.jvalog.resource;

import java.util.Collection;

import javax.jdo.Query;

import net.asfun.jvalog.common.Jdoer;
import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.Meter;
import net.asfun.jvalog.entity.Sort;
import net.asfun.jvalog.util.Bridge;

import com.google.appengine.api.datastore.Key;

public class MeterDao {
	
	public static int getCount(Key owner) {
		Jdoer<Meter> jdm = JdoerFactory.jdoMeter;
		Query q = jdm.prepareQuery();
		q.setFilter("owner == mykey");
		q.declareParameters("com.google.appengine.api.datastore.Key mykey");
		Meter meter =  jdm.unique(q, owner);
		if ( meter == null ) return 0;
		return meter.getCount();
	}
	
	public static void setCount(Key owner, int number) {
		Jdoer<Meter> jdm = JdoerFactory.jdoMeter;
		Query q = jdm.prepareQuery();
		q.setFilter("owner == mykey");
		q.declareParameters("com.google.appengine.api.datastore.Key mykey");
		Meter meter =  jdm.unique(q, owner);
		if ( meter == null) {
			meter = new Meter();
			meter.setCount(number);
			meter.setOwner(owner);
			jdm.save(meter);
		} else {
			meter.setCount(number);
		}
	}
	
	public static void delCount(Key owner) {
		Jdoer<Meter> jdm = JdoerFactory.jdoMeter;
		Query q = jdm.prepareQuery();
		q.setFilter("owner == mykey");
		q.declareParameters("com.google.appengine.api.datastore.Key mykey");
		Meter meter =  jdm.unique(q, owner);
		if ( meter != null ) {
			jdm.delete(meter);
		}
	}

	/**
	 * just count category right now
	 */
	public static void reBuild() {
		Collection<Sort> clt1 = JdoerFactory.jdoSort.all();
		for(Sort sort : clt1 ) {
			setCount(sort.getKey(), Bridge.getRelationsByRight(sort.getKey(), Bridge.POST_CATEGORY).size());
		}
	}

	public static void countDown(Key owner, int distance) {
		Jdoer<Meter> jdm = JdoerFactory.jdoMeter;
		Query q = jdm.prepareQuery();
		q.setFilter("owner == mykey");
		q.declareParameters("com.google.appengine.api.datastore.Key mykey");
		Meter meter =  jdm.unique(q, owner);
		if ( meter == null) {
			meter = new Meter();
			meter.setCount(0);
			meter.setOwner(owner);
			jdm.save(meter);
		} else {
			int count = meter.getCount() - distance;
			if ( count < 0 ) count = 0;
			meter.setCount(count);
		}
	}
	
	public static void countUp(Key owner, int distance) {
		Jdoer<Meter> jdm = JdoerFactory.jdoMeter;
		Query q = jdm.prepareQuery();
		q.setFilter("owner == mykey");
		q.declareParameters("com.google.appengine.api.datastore.Key mykey");
		Meter meter =  jdm.unique(q, owner);
		if ( meter == null) {
			meter = new Meter();
			meter.setCount(distance);
			meter.setOwner(owner);
			jdm.save(meter);
		} else {
			int count = meter.getCount() + distance;
			meter.setCount(count);
		}
	}
}
